package com.daffodil.monitor.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Service;

import com.alibaba.cloud.nacos.NacosServiceInstance;
import com.alibaba.cloud.nacos.discovery.NacosServiceDiscovery;
import com.alibaba.nacos.api.exception.NacosException;
import com.daffodil.monitor.service.INacosService;
import com.daffodil.util.StringUtils;

import cn.hutool.crypto.digest.DigestUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @author yweijian
 * @date 2022年10月13日
 * @version 2.0.0
 * @description
 */
@Slf4j
@Service
public class NacosServiceImpl implements INacosService {
    
    private static ConcurrentHashMap<String, NacosServiceInstance> nacosServiceInstanceHashMap = new ConcurrentHashMap<String, NacosServiceInstance>();

    @Autowired
    private NacosServiceDiscovery nacosServiceDiscovery;
    
    @Override
    public List<NacosServiceInstance> selectNacosServiceList() {
        
        List<String> list = null;
        try {
            list = nacosServiceDiscovery.getServices();
        } catch (NacosException e) {
            log.error(e.getMessage(), e);
        }
        
        List<ServiceInstance> services = new ArrayList<ServiceInstance>();
        if(StringUtils.isNotEmpty(list)) {
            for (int i = 0; i < list.size(); i++) {
                try {
                    services.addAll(nacosServiceDiscovery.getInstances(list.get(i)));
                } catch (NacosException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        
        nacosServiceInstanceHashMap.clear();
        
        return services.stream().map(service -> {
            NacosServiceInstance instance = (NacosServiceInstance) service;
            String hashKey = DigestUtil.md5Hex(instance.getServiceId() + instance.getHost() + instance.getPort());
            nacosServiceInstanceHashMap.put(hashKey, instance);
            return instance;
        }).collect(Collectors.toList());
    }

    @Override
    public NacosServiceInstance selectNacosService(String hashKey) {
        return nacosServiceInstanceHashMap.get(hashKey);
    }

}
